package com.manage.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.manage.config.model.Config;
import com.manage.util.SystemUtil;

public class HtmlFilter
		implements Filter {

	static final Logger logger = Logger.getLogger(HtmlFilter.class);

	protected FilterConfig config;

	@Override
	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain)
			throws IOException, ServletException {
		if (SystemUtil.isDebug()) {
			filterChain.doFilter(arg0, arg1);
		} else {
			HttpServletRequest request = (HttpServletRequest) arg0;
			HttpServletResponse response = (HttpServletResponse) arg1;
			String url = request.getRequestURI();
			logger.info("HtmlFilter start url: " + url);
			if (url.indexOf("login") != -1) {
				filterChain.doFilter(arg0, arg1);
				return;
			} else {
				Object obj = request.getSession().getAttribute(Config.USER_SESSION);
				if (obj == null) {
					response.sendRedirect("/login.html");
				} else {
					filterChain.doFilter(arg0, arg1);
				}
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;
	}
}
